package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRegistService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 *
 * 登录检查拦截器
 *           1.8之后使用拦截器类实现 HandlerInterceptor 接口，里面的方法默认实现
 * */
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRegistService userInfoRegistService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String token = CookieUtil.getToken(request);
//        UserInfo user = userInfoRegistService.getUserByToken(token);
//        if (user ==null){
//
//            response.sendRedirect("/login.html");
//            return false;
//        }

        UserInfo user =null;
        //获取访问方法是否有贴注解
        if (handler instanceof HandlerMethod) {
            //前面个if判断是否可以强转
            HandlerMethod mh = (HandlerMethod) handler;
            //如果有贴注解
            if (mh.hasMethodAnnotation(RequireLogin.class)) {
                String token = CookieUtil.getToken(request);
                 user = userInfoRegistService.getUserByToken(token);
                if (user == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        String token = CookieUtil.getToken(request);
        user = userInfoRegistService.getUserByToken(token);
        request.getSession().setAttribute("userInfo",user);
        return true;
    }
}
